package view;

import app.App;
import component.CustomJTable;
import model.Product;
import model.SaleRecord;
import model.User;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SaleView extends JFrame{

    private final static int INIT_W = 1000;  //窗体初始宽度
    private final static int INIT_H = 650;  //窗体初始高度

    private JTable table_sale;
    private JPanel contentPane;
    private JFormattedTextField tf_productId;
    private JTextField l_serialNum;
    private JTextField tf_total;
    private JButton btn_checkout;
    private JButton btn_discount;
    private JLabel l_productCount;
    private JButton btn_add;
    private JTextField tf_discount;
    private JTextField tf_final;
    private JComboBox<String> cb_cashier;
    private JButton btn_del;

    DefaultTableModel tableModel_sale;
    List<Product> currentSaleList = new ArrayList<>();
    List<SaleRecord> saleRecordList;
    List<User> cashiers = new ArrayList<>();
    User currentCashier;

    float discountMoney = 0;

    private void createUIComponents() {
        table_sale = new CustomJTable(new String[]{"商品号","商品名","单价","数量","总金额"});
        tableModel_sale = (DefaultTableModel) table_sale.getModel();

        //输入字符限制
        NumberFormat nf = NumberFormat.getIntegerInstance();
        nf.setGroupingUsed(false);
        tf_productId = new JFormattedTextField(nf);
    }

    public SaleView() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setTitle("超市零售界面");
        setMinimumSize(new Dimension(INIT_W,INIT_H));
        setContentPane(contentPane);
        pack();
        setVisible(true);
        //居中
        Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setBounds(p.x - INIT_W / 2, p.y - INIT_H / 2, INIT_W, INIT_H);

        //更新收银员列表
        List<User> userList = App.currentUserList;
        if (userList != null) {
            for (User user : userList) {
                if (user.getJobId() == 0 ||user.getJobId() == 1)//只添加管理员与销售员
                    cashiers.add(user);
            }
        }
        //选择与当前用户作为收银员
        for (User cashier : cashiers) {
            cb_cashier.addItem(cashier.getUserName());
            if (cashier.getUserId() == App.loggedUser.getUserId()){
                currentCashier = cashier;
                cb_cashier.setSelectedItem(currentCashier.getUserName());
            }
        }

        //下拉框监听器
        cb_cashier.addItemListener(e -> {
            User cashier = cashiers.get(cb_cashier.getSelectedIndex());
            if (cashier.getUserId() != currentCashier.getUserId()){
                JPanel panel = new JPanel();
                JLabel label = new JLabel("输入密码:");
                JPasswordField pass = new JPasswordField(10);
                panel.add(label);
                panel.add(pass);
                String[] options = new String[]{"确定", "取消"};
                int option = JOptionPane.showOptionDialog(contentPane, panel, "验证密码",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                        null, options, options[1]);
                String password = String.valueOf(pass.getPassword());
                if (option == 0) {
                    if (!password.isEmpty() && cashier.getPassword().equals(password)) {//点击确定
                        System.out.println("密码正确,密码是: " + password);
                        currentCashier = cashier;
                    } else {
                        cb_cashier.setSelectedItem(currentCashier.getUserName());
                        JOptionPane.showMessageDialog(contentPane, "密码错误！\n\n收银员切换失败", null, JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        //设置新的流水号
        l_serialNum.setText(String.valueOf(SaleRecord.getNewSerialNum()));

        //添加商品按钮
        btn_add.addActionListener(e -> {
            if (!tf_productId.getText().isBlank()) {
                int productId = Integer.parseInt(tf_productId.getText());
                Product product = Product.getProduct(productId);
                if (product != null){
                    String input = JOptionPane.showInputDialog(contentPane, "输入数量：");
                    if (input != null && !input.isBlank()) {
                        try {
                            int count = Integer.parseInt(input);
                            if (count > 0) {
                                product.setQuantity(count);
                                onAddProduct(product);
                            }
                            else {
                                JOptionPane.showMessageDialog(contentPane, "请输入正确数值(大于0的整数)", null, JOptionPane.ERROR_MESSAGE);
                            }
                        }
                        catch (NumberFormatException exception){
                            JOptionPane.showMessageDialog(contentPane, "请输入正确数值(大于0的整数)", null, JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
                else {
                    JOptionPane.showMessageDialog(contentPane, "商品不存在！", null, JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        //打折按钮
        btn_discount.addActionListener(e -> {
            float discount = Float.parseFloat(JOptionPane.showInputDialog(contentPane,"输入折扣（0.01~0.99）："));
            if (discount >= 0.01 && discount <= 0.99) {
                discount = 1 - discount;
                discountMoney = Float.parseFloat(tf_total.getText()) * discount;//计算折扣金额
                tf_discount.setText(String.format("%.2f", discountMoney));

            }
            else {
                JOptionPane.showMessageDialog(contentPane, "非法数值！", null, JOptionPane.ERROR_MESSAGE);
            }
        });
        //删除商品按钮
        btn_del.addActionListener(e -> {
            int row = table_sale.getSelectedRow();
            if (row != -1) {
                currentSaleList.remove(row);
                notifySaleRecordListChanged();
            }
        });
        //结算按钮
        btn_checkout.addActionListener(e -> {
            saleRecordList = getSaleRecordList();
            if (saleRecordList.size() != 0) {
                if (JOptionPane.showConfirmDialog(contentPane, getCheckOutMessage(), "确定结算？", JOptionPane.YES_NO_OPTION) == 0) {
                    if (SaleRecord.SaleProducts(saleRecordList)) {
                        JOptionPane.showMessageDialog(contentPane, "结算成功！", null, JOptionPane.INFORMATION_MESSAGE);
                        onCheckOuted();
                    } else {
                        JOptionPane.showMessageDialog(contentPane, "结算失败！", null, JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
            else {
                JOptionPane.showMessageDialog(contentPane, "当前零售列表为空！", null, JOptionPane.ERROR_MESSAGE);
            }
        });
        //打折输入框
        tf_discount.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {change();}
            public void removeUpdate(DocumentEvent e) {change();}
            public void insertUpdate(DocumentEvent e) {change();}
            private void change() {
                String str_discountMoney = tf_discount.getText();
                if (str_discountMoney != null && !str_discountMoney.isBlank()){
                    discountMoney = Float.parseFloat(str_discountMoney);
                    System.out.println("折扣金额改变" + discountMoney);
                    float totalMoney = Float.parseFloat(tf_total.getText());
                    tf_final.setText(String.format("%.2f", totalMoney - discountMoney));
                }
            }
        });
    }

    private String getCheckOutMessage() {
        StringBuilder sb = new StringBuilder();
        sb.append("结算信息如下：\n\n");
        sb.append("流水号：").append(saleRecordList.get(0).getSerialNum()).append("\n\n");

        int n = 1;
        for (SaleRecord saleRecord : saleRecordList) {
            sb.append("商品：\n");
            sb.append(n++).append('.').append(saleRecord.getProductName()).append("：    ");
            sb.append("单价(折后)：￥").append(String.format("%.2f", saleRecord.getSellingPrice())).append("    ");
            sb.append("数量：").append(saleRecord.getCount()).append("    ");
            sb.append("总价：￥").append(String.format("%.2f", saleRecord.getSellingPrice()*saleRecord.getCount())).append("        \n");
        }

        sb.append("\n总价：￥").append(tf_total.getText()).append("\n");
        sb.append("折扣：￥").append(discountMoney).append("\n");
        sb.append("应收：￥").append(tf_final.getText()).append("\n\n");

        sb.append("确定结算？").append("\n");
        return sb.toString();
    }

    //结算后处理
    private void onCheckOuted() {
        //设置新的流水号
        l_serialNum.setText(String.valueOf(SaleRecord.getNewSerialNum()));
        //清空列表
        currentSaleList = new ArrayList<>();
        //打折金额清零
        tf_discount.setText("0.00");

        App.notifySaleRecordListChanged();
    }

    //当添加商品时，添加商品或修改数量
    private void onAddProduct(Product newProduct) {
        tf_productId.setText("");

        //获取已在购物列表的商品的Id列表
        boolean isNew = true;
        for (Product inList : currentSaleList) {//遍历销售列表
            if (inList.getProductId() == newProduct.getProductId()) {//找到id号相同的商品
                isNew = false;//商品已存在
                inList.setQuantity(inList.getQuantity() + newProduct.getQuantity());//修改数量
                break;
            }
        }
        if (isNew) {//商品不存在
            currentSaleList.add(newProduct);
        }
        //更新表格
        App.notifySaleRecordListChanged();
    }

    public void notifySaleRecordListChanged() {
        System.out.println("零售列表更新：\n"+currentSaleList);

        //更新表格
        tableModel_sale.setRowCount(0);
        if (currentSaleList != null) {
            for (Product product : currentSaleList) {
                tableModel_sale.addRow(product.toSaleListObjectArray());
            }
            CustomJTable.resizeColumnWidth(table_sale);

            //更新总金额和商品总数
            float totalMoney = 0;
            int productCount = 0;
            for (Product saleProduct : currentSaleList) {
                totalMoney += saleProduct.getQuantity()*saleProduct.getSellingPrice();//总金额 += 商品个数*售价
                productCount += saleProduct.getQuantity();
            }
            tf_total.setText(String.format("%.2f", totalMoney));
            l_productCount.setText(String.valueOf(productCount));

            //更新应收金额
            float finalMoney = totalMoney - discountMoney;
            tf_final.setText(String.format("%.2f", finalMoney));
        }
        else {//列表为空则清零
            tf_total.setText("0.00");
            l_productCount.setText("0");
            tf_final.setText("0.00");
        }
    }

    //获得销售记录列表
    private List<SaleRecord> getSaleRecordList() {
        List<SaleRecord> saleRecordList = new ArrayList<>();
        for (Product product : currentSaleList) {
            SaleRecord saleRecord = new SaleRecord();
            saleRecord.setSerialNum(Integer.parseInt(l_serialNum.getText()));
            saleRecord.setCashier(currentCashier.getUserId());
            saleRecord.setProductId(product.getProductId());
            saleRecord.setProductName(product.getProductName());
            System.out.println("当前打折金额："+ discountMoney+"，商品数量："+currentSaleList.size());
            saleRecord.setSellingPrice(product.getSellingPrice() - (discountMoney / currentSaleList.size() / product.getQuantity()));
            saleRecord.setCount(product.getQuantity());
            saleRecord.setSaleTime(new Timestamp(new Date().getTime()));
            saleRecord.setProduct(product);
            saleRecordList.add(saleRecord);
        }
        return saleRecordList;
    }
}
